package com.xoa.service.hr;

import com.xoa.controller.hr.HrRehabController;
import com.xoa.dao.department.DepartmentMapper;
import com.xoa.dao.hr.HrRehabMapper;
import com.xoa.model.hr.HrRehab;
import com.xoa.model.users.UserPriv;
import com.xoa.util.ExcelUtil;
import com.xoa.util.ToJson;
import com.xoa.util.common.StringUtils;
import com.xoa.util.page.PageParams;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

@Service
public class HrRehabService {
    @Autowired
    private HrRehabMapper hrRehabMapper;
    @Resource
    private DepartmentMapper departmentMapper;
    /**
     * 添加
     * 郭心雨
     * 2018.07.19
     * @param hrRehab
     * @return
     */
    public ToJson addRehab(HrRehab hrRehab) {
        ToJson toJson=new ToJson();
        int count=hrRehabMapper.insertSelective(hrRehab);
        if(count>0){
            toJson.setMsg("ok");
            toJson.setFlag(0);
        }else{
            toJson.setMsg("err");
            toJson.setFlag(1);
        }
        return toJson;
    }

    /**
     * 删除
     * 郭心雨
     * 2018.07.19
     * @param rehabid
     * @return
     */
    public ToJson delRehab(Integer[] rehabid) {
        ToJson toJson=new ToJson();
        int count=hrRehabMapper.deleteByWexperienceId(rehabid);
        if(count>0){
            toJson.setMsg("ok");
            toJson.setFlag(0);
        }else{
            toJson.setMsg("err");
            toJson.setFlag(1);
        }
        return toJson;
    }
    /**
     * 修改
     * 郭心雨
     * 2018.07.19
     * @param hrRehab
     * @return
     */
    public ToJson modifyRehab(HrRehab hrRehab) {
        ToJson toJson=new ToJson();
        int count=hrRehabMapper.updateByPrimaryKeySelective(hrRehab);
        if(count>0){
            toJson.setMsg("ok");
            toJson.setFlag(0);
        }else{
            toJson.setMsg("err");
            toJson.setFlag(1);
        }
        return toJson;
    }

    /**
     * 根据id查询详情
     * 郭心雨
     * 2018.07.19
     * @param rehabid
     * @return
     */
    public ToJson selRehabById(Integer rehabid) {
        ToJson toJson=new ToJson();
        HrRehab hrRehab=hrRehabMapper.selRehabById(rehabid);
        if(hrRehab!=null){
            toJson.setFlag(0);
            toJson.setMsg("ok");
            toJson.setObject(hrRehab);
        }else{
            toJson.setFlag(1);
            toJson.setMsg("err");
        }
        return toJson;
    }

    /**
     * 查看列表
     * 郭心雨
     * 2018.07.19
     * @return
     */
    public ToJson selAllRehab(Integer page,Integer pageSize,Boolean useFlag) {
        ToJson toJson=new ToJson();
        PageParams pageParams = new PageParams();
        pageParams.setPage(page);
        pageParams.setPageSize(pageSize);
        pageParams.setUseFlag(useFlag);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("page", pageParams);
        List<HrRehab> hrRehabList=hrRehabMapper.selAllRehab(map);
        if(hrRehabList.size()>0){
            toJson.setFlag(0);
            toJson.setMsg("ok");
            toJson.setObj(hrRehabList);
        }else{
            toJson.setFlag(1);
            toJson.setMsg("err");
        }
        return toJson;
    }
    /**
     * 模糊查询
     * 郭心雨
     * 2018.07.20
     * @param hrRehab
     * @param page
     * @param pageSize
     * @param useFlag
     * @return
     */
    public ToJson selAllRehabBy(HrRehab hrRehab, Integer page, Integer pageSize, Boolean useFlag) {
        ToJson toJson=new ToJson();
        PageParams pageParams = new PageParams();
        pageParams.setPage(page);
        pageParams.setPageSize(pageSize);
        pageParams.setUseFlag(useFlag);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("page", pageParams);
        map.put("hrRehab", hrRehab);
        List<HrRehab> hrRehabList=hrRehabMapper.selAllRehabMo(map);
        if(hrRehabList.size()>0){
            toJson.setFlag(0);
            toJson.setMsg("ok");
            toJson.setObj(hrRehabList);
        }else{
            toJson.setFlag(1);
            toJson.setMsg("err");
        }
        return toJson;
    }

    public ToJson<HrRehab> inputFixAsserts(HttpServletRequest request, HttpServletResponse response, MultipartFile file, HttpSession session) {
        ToJson<HrRehab> json = new ToJson<HrRehab>();
        // 成功次数
        Integer successCount = 0;
        InputStream in=null;
        try {
            //判读当前系统
            //读取配置文件
            ResourceBundle rb = ResourceBundle.getBundle("upload");
            String osName = System.getProperty("os.name");
            StringBuffer path = new StringBuffer();
                StringBuffer buffer=new StringBuffer();
        if(osName.toLowerCase().startsWith("win")){
            //sb=sb.append(rb.getString("upload.win"));
            //判断路径是否是相对路径，如果是的话，加上运行的路径
            String uploadPath = rb.getString("upload.win");
            if(uploadPath.indexOf(":")==-1){
                //获取运行时的路径
                String basePath = this.getClass().getClassLoader().getResource(".").getPath()+ File.pathSeparator;
                //获取截取后的路径
                String str2 = "";
                if(basePath.indexOf("/xoa")!=-1){
                    //获取字符串的长度
                    int length = basePath.length();
                    //返回指定字符在此字符串中第一次出现处的索引
                    int index = basePath.indexOf("/xoa");
                    //从指定位置开始到指定位置结束截取字符串
                    str2=basePath.substring(0,index);
                }
                path = path.append(str2 + "/xoa");
            }
            path.append(uploadPath);
            buffer=buffer.append(rb.getString("upload.win"));
        }else{
            path=path.append(rb.getString("upload.linux"));
            buffer=buffer.append(rb.getString("upload.linux"));
        }

            // 判断是否为空文件
            if (file.isEmpty()) {
                json.setMsg("请上传文件！");
                json.setFlag(1);
                return json;
            } else {
                String fileName = file.getOriginalFilename();
                if (fileName.endsWith(".xls") || fileName.endsWith(".xlsx")) {
                    String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                    int pos = fileName.indexOf(".");
                    String extName = fileName.substring(pos);
                    String newFileName = uuid + extName;
                    File dest = new File(path.toString(), newFileName);
                    file.transferTo(dest);
                    // 将文件上传成功后进行读取文件
                    // 进行读取的路径
                    String readPath = path.append("\\"+newFileName).toString();
                    in = new FileInputStream(readPath);
                    HSSFWorkbook excelObj = new HSSFWorkbook(in);
                    HSSFSheet sheetObj = excelObj.getSheetAt(0);
                    Row row = sheetObj.getRow(0);
                    int colNum = row.getPhysicalNumberOfCells();
                    int lastRowNum = sheetObj.getLastRowNum();
                    List<HrRehab> saveList = new ArrayList<HrRehab>();
                    HrRehab hrRehab=null;
                    for (int i = 1; i <= lastRowNum; i++) {
                        hrRehab =new HrRehab();
                        row = sheetObj.getRow(i);
                        if (row != null) {
                            for (int j = 0; j < colNum; j++) {
                                Cell cell = row.getCell(j);
                                if (cell != null) {
                                    switch (j) {
                                        case 0:
                                            //姓名
                                            hrRehab.setName(getCellValue(cell));
                                            break;
                                        case 1:
                                           //担任职务
                                            hrRehab.setPost(getCellValue(cell));
                                            break;
                                        case 2:
                                            //申请日期
                                            hrRehab.setApplyData(getCellValue(cell));
                                            break;
                                        case 3:
                                            //实际复职日期
                                            hrRehab.setActualData(getCellValue(cell));
                                            break;
                                        case 4:
                                            //复职手续办理
                                            hrRehab.setFormality(getCellValue(cell));
                                            break;
                                        case 5:
                                            //复职类型
                                            hrRehab.setRehabType(getCellValue(cell));
                                            break;
                                        case 6:
                                            //复职部门
                                            List<String> parentList = departmentMapper.getDeptIdByDeptName(getCellValue(cell));
                                            String deptIdByDeptName="";
                                            if(parentList.size()>0){
                                                deptIdByDeptName=parentList.get(0);
                                            }
                                            if(!StringUtils.checkNull(deptIdByDeptName)){
                                                hrRehab.setRehabDept(deptIdByDeptName);
                                            }
                                            break;
                                        case 7:
                                            //拟复职日期
                                            hrRehab.setNiData(String.valueOf(getCellValue(cell)));
                                            break;
                                        case 8:
                                            //工资恢复日期
                                            hrRehab.setWegsdata(getCellValue(cell));
                                            break;
                                        case 9:
                                            // 复职说明
                                            hrRehab.setExplain(String.valueOf(getCellValue(cell)));
                                            break;
                                        case 10:
                                            // 备注
                                            hrRehab.setRemarks(getCellValue(cell));
                                            break;
                                        case 11:
                                            //登记时间
                                            hrRehab.setRegistrationData(String.valueOf(getCellValue(cell)));
                                            break;
                                    }
                                }
                            }
                            if (hrRehab != null) {
                                int i1 = hrRehabMapper.insertSelective(hrRehab);
                                if(i1>0){
                                    successCount++;
                                }
                            }
                        }
                    }
                } else {
                    json.setMsg("file type error!");
                    json.setFlag(1);
                    return json;
                }
            }
            json.setTotleNum(successCount);
            json.setMsg("ok");
            json.setFlag(0);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg("err");
            json.setFlag(1);
        } finally {
            try {
                if(in!=null){
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return json;
    }
    private String getCellValue(Cell cell) {

        Object value=null;
        switch (cell.getCellType()){
            case STRING:
                value = cell.getStringCellValue();
                break;
            case NUMERIC:
                value = (int)cell.getNumericCellValue();
                break;
            default:
                value = cell.getStringCellValue();
                break;
        }
        return String.valueOf(value);
    }

//    public ToJson<HrCode>  selectType(String parentNo) {
//        ToJson<HrCode>  toJson=new ToJson<HrCode> ();
//        List<HrCode> hrCodeList=hrCodeMapper.selectByParentNo(parentNo);
//        if (hrCodeList.size()>0){
//            toJson.setObj(hrCodeList);
//            toJson.setMsg("ok");
//            toJson.setFlag(0);
//        }else{
//            toJson.setMsg("ok");
//            toJson.setFlag(0);
//        }
//        return toJson;
//    }
}
